using DynamicModelDemo.EntityFramework;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DynamicModelDemo
{
    public class TestHostService : BackgroundService, IHostedService
    {
        public ILogger<TestHostService> Logger { get; }

        public TestHostService(ILogger<TestHostService> logger)
        {
            Logger = logger;
        }

        async Task AddOneAsync()
        {
            Logger.LogInformation("准备写入一行数据");
            using var dbContext = new MyDbContext();
            var entity = new Entities.StudentEntity(Guid.NewGuid());
            entity.Name = DateTime.Now.ToShortDateString();
            await dbContext.Students.AddAsync(entity);
            await dbContext.SaveChangesAsync();
            Logger.LogInformation($@"写入一行数据{entity.Name}@{entity.Id}");
        }

        async Task ReadOneAsync()
        {
            Logger.LogInformation("准备读取一行数据");
            using var dbContext = new MyDbContext();
            var entity = await dbContext.Students.FirstOrDefaultAsync();
            Logger.LogInformation("读取一行数据:");
            Logger.LogInformation(JsonConvert.SerializeObject(entity));
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                await AddOneAsync();
                await ReadOneAsync();
            }
            catch (Exception exp)
            {
                Logger.LogError(exp, "测试");
            }
        }
    }
}
